package com.jin.crud.controller;

import com.jin.crud.bean.LoginBody;
import com.jin.crud.bean.SysMenu;
import com.jin.crud.bean.SysUser;
import com.jin.crud.bean.vo.RouterVo;
import com.jin.crud.common.constants.Constants;
import com.jin.crud.common.utils.ResultUtil;
import com.jin.crud.common.utils.SecurityUtils;
import com.jin.crud.service.SysLoginService;
import com.jin.crud.service.SysMenuService;
import com.jin.crud.service.SysPermissionService;
import com.jin.crud.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author yuxuejin
 * @Date 2021/11/22 14:34
 * @Description:
 */
@Slf4j
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public ResultUtil login(LoginBody loginBody) {
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.TOKEN, loginService.login(loginBody));
        return ResultUtil.resultSuccess(map);
    }

    @PostMapping(value = "/logoutSys")
    public ResultUtil logout() {
        loginService.logout();
        return ResultUtil.resultSuccess();
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public ResultUtil getInfo() {
        String id = SecurityUtils.getLoginUser().getUserId();
        SysUser user = userService.getUser(id);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return ResultUtil.resultSuccess(map);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public ResultUtil<List<RouterVo>> getRouters() {
        String userId = SecurityUtils.getLoginUser().getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return ResultUtil.resultSuccess(menuService.buildMenus(menus));
    }

}
